define(function (require, exports, module) {
    require ("jquery");
    require ("dialog");

    (function($){
        var pluginName = "validate";
        /*
         * 参数说明：
         **/
        var defaults = {
            skin: 'u-invalid',
            onPass: false
        };
        var prompts = {
            radio: '请选择一个选项',
            checkbox: '如果要继续，请选中此框',
            select: '请选择列表中的一项',
            empty: '请输入此字段',
            chinese: '只允许输入中文字符',
            english: '只允许输入英文字符',
            email: '请输入有效的邮件地址',
            number: '请输入正确的数字',
            int: '请输入正确的整数',
            mobile: '请输入有效的手机号码',
            url: '请输入有效的网站地址',
            code: '请输入有效的邮编',
            date: '请输入有效的日期',
            pattern: '内容格式不符合要求',
            decimal: "请输入正确的金额"
        };
        var rules = {
            decimal: /^[0-9]+\.{0,2}[0-9]{0,2}$/,
            chinese: /^[\u4e00-\u9fa5]+$/,
            noChinese: /^[\d ]+$/,
            english: /^[A-Za-z]+$/,
            email: /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/,
            number: /^\-?\d+(\.\d+)?$/,
            int: /^-?\d+$/,
            mobile: /^1\d{10}$/,
            url: /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/,
            date: /^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/,
            code: /^\d{6}$/
        };
        var checking = function(elem){
            var noError = true;
            $.each(elem,function(){
                var _elem = $(this);
                var el = this,
                    type = _elem.attr("type"),
                    tag = el.tagName.toLowerCase(),
                    isRequired = (this.getAttribute('required') != null),
                    pattern = $.trim(this.getAttribute('pattern')) ? $.trim(this.getAttribute('pattern')) : null;
                /**
                 * 验证内容
                 * input [type, required, multiple, pattern, max, min]
                 * radio [required]
                 * checkbox [required]
                 * select [value]
                 * textarea [required, max, min]
                 * pattern = {
                 *      chinese: 中文,
                 *      english: 英文,
                 *      email: 邮箱,
                 *      number: 数字，
                 *      digits: 整数
                 *      tel: 手机号码,
                 *      url: 网址,
                 *      date: 日期,
                 *      code: 邮编,
                 * }
                 */
                if (!el.disabled && type != 'submit' && type != 'resize' && type != 'button' && type != 'file' && type != 'image' && tag != 'img') {
                    //radio复选框，是否必选
                    if (type == 'radio' && isRequired) {
                        //单选框，只需验证是否必选，同一name单选组只有要一个设置required即可
                        var radios = el.name ? _elem.siblings(':radio[name="' + el.name + '"]') : $(el),
                            radioPass = false;
                        $.each(radios, function () {
                            if (this.checked) {
                                radioPass = true;
                                return false;
                            }
                        });
                        if (!radioPass) {
                            openDialog(prompts['checkbox'],radios[0]);
                        }
                    } else if (type == 'checkbox' && isRequired && !el.checked) {
                        noError = false;
                        openDialog(prompts['checkbox'],el);
                    }
                    //select下拉框，是否必选，并且value != ''
                    else if (tag == 'select' && isRequired && !el.value) {
                        noError = false;
                        openDialog( prompts['select'],el);
                    }
                    //输入框为空验证。
                    else if (isRequired && (type != 'password' ? $.trim(el.value) : el.value) == '') {
                        noError = false;
                        openDialog(prompts['empty'],el);
                    }
                    //输入框格式 以及范围验证
                    else if ((tag == 'textarea' || type == 'text' || type == 'password' || type == 'hidden' || type == 'checkbox') && (isRequired || el.value != '')) {
                        //如果pattern内容为正则表达式 按正则表达进行验证
                        if (pattern != null && pattern.indexOf('/') == 0 && !((new RegExp(pattern, 'i')).test(el.value))) {
                            noError = false;
                            openDialog(prompts['pattern'],el);
                        }
                        //如果rules[pattern] != 'undefined' 调用相应的规则验证
                        else if (pattern != null && rules[pattern] != 'undefined' && ((typeof(rules[pattern]) == 'object' && !rules[pattern].test(el.value)) || (typeof(rules[pattern]) == 'function' && !rules[pattern](el.value)))) {
                            noError = false;
                            openDialog(prompts[pattern],el);
                        }
                        //对值的范围验证
                        else {
                            var ret = range.call(el);
                            if (!ret.state) {
                                openDialog(ret.msg,el);
                                noError = false;
                            }
                        }
                    }
                    //文件上传
                    else if(isRequired &&  type=="file"){
                        if($.trim(el.value) != ''){
                            noError = false;
                            openDialog(prompts['pattern'],el);
                        }
                    }
                }
                if (!noError) {
                    return false;
                }
            });
            return noError;
        };

        /*
        * 范围检验
        * @param elem
        * @returns {{state: boolean, msg: string}}
        */
        var range = function(elem){
            var el = $(this),
                tag = el[0].tagName.toLowerCase(),
                type = el.attr('type'),
                pattern = this.getAttribute('pattern') ? this.getAttribute('pattern') : null,
                min = $.trim(el.attr('min')) ? $.trim(el.attr('min')) : null,
                max = $.trim(el.attr('max')) ? $.trim(el.attr('max')) : null;

            var state = true,
                msg = '';

            if (min || max) {
                //min max 范围验证 可判断4种 [字符串长度范围, 数值范围, 时间范围, 复选框选择数量]
                if (pattern == 'date') {
                    var valDate = newDate(el.val()),
                        minDate = newDate(min),
                        maxDate = newDate(max);
                    if (minDate && valDate < minDate) {
                        state = false;
                        msg = '时间必须大于或等于' + min;
                    } else if (maxDate && valDate > maxDate) {
                        state = false;
                        msg = '时间必须小于或等于' + max;
                    }
                } else if (pattern == 'number' || pattern == 'int') {
                    var val = parseFloat(el.val());
                    min = min ? parseFloat(min) : min;
                    max = max ? parseFloat(max) : max;
                    if (min && val < min) {
                        state = false;
                        msg = '值必须大于或等于' + min;
                    } else if (max && val > max) {
                        state = false;
                        msg = '值必须小于或等于' + max;
                    }
                } else if (type == 'checkbox' && min) {
                    var checkboxArr = el[0].name ? formElem.find(':checkbox[name="' + el[0].name + '"]') : el,
                        checkCount = 0;

                    $.each(checkboxArr, function () {
                        if (this.checked) {
                            checkCount++
                        }
                    });
                    if (checkCount < min) {
                        state = false;
                        msg = '最少选择' + min + '项';
                    }
                } else {
                    var len = el.val().length;
                    if (min && len < min) {
                        state = false;
                        msg = '至少输入' + min + '个字符';
                    } else if (max && len > max) {
                        state = false;
                        msg = '最多输入' + max + '个字符';
                    }
                }
            }
            return {
                state: state,
                msg: msg
            };
        };
        function Plugin(elem,options){
            var self = this,
                elem = $(elem),
                opts = $.extend({}, defaults, options);

            elem.attr('novalidate', 'novalidate').on('submit', function (e) {
                e.preventDefault();
                var _elements = elem.find(':input');
                if (checking(_elements) && opts.onPass) {
                    return opts.onPass.call(elem, e);
                }
                return false;
            });
        }
        $.fn[pluginName] = function(options){
            return this.each(function(){
                if(!$.data(this,"Plugin_"+ pluginName)){
                    $.data(this,"Plugin_"+ pluginName, new Plugin(this,options));
                };
            })
        }
    })(jQuery);

    (function($){
        var pluginName = "form";
        /**
        * 参数说明：
        * formData {} 传进来的参数
        * onSubmitBefore :function(elem){} 提交前的操作
        * onError: function(ret || null){} 当错误时的操作 @params ajax返回的值
        * onAccept:function(ret){} 当成功时的操作 @params ajax返回的值
        **/
        var defaults = {
            ajax: true,
            formData: null,
            onSubmitBefore: false,
            onError: false,
            onAccept: false
        };
        function Plugin(elem, options){
             var self = this,
                 elem = $(elem),
                 opts = $.extend({},defaults,options);
             self.elem = elem;
             var req = null;
                oSubmit = elem.find("input[type='submit']" || "button[type='submit']");
                elem.validate({
                    onPass:function(e){
                      if(req){
                          return false;
                      }
                      if (opts.onSubmitBefore && opts.onSubmitBefore.call(elem, self) == false) {
                            return false;
                      }
                      if(opts.ajax){
                           e.preventDefault();
                           oSubmit.addClass('z-dis');
                           req =$.ajax({
                               type:"post",
                               data:opts.formData ? $.extend(opts.formData, elem.serialize()) : elem.serialize(),
                               dataType:"json",
                               url:elem.attr('action'),
                               success:function(ret){
                                   req = null;
                                   oSubmit.removeClass('z-dis');
                                   //成功
                                   if (ret.succeed) {
                                       if (opts.onAccept) {
                                           opts.onAccept(ret);
                                       }
                                   } else {
                                       if (opts.onError) {
                                           opts.onError(ret);
                                        }
                                   }
                               },
                               error:function(ret,err){
                                   req = null;
                                   oSubmit.removeClass('z-dis');
                                   openDialog('服务器繁忙，连接失败！');
                                   if (opts.onError) {
                                       opts.onError(null);
                                   }
                               }
                           });
                       }
                    }
                });
             return elem;
        }
        $.fn[pluginName] = function(options){
            return this.each(function(){
                if(!$.data(this,"Plugin_"+ pluginName)){
                    $.data(this,"Plugin_"+ pluginName, new Plugin(this,options));
                };
            })
        }
    })(jQuery);


    var openDialog = function(msg,obj){
        if(obj){
            var d = dialog({
                content: msg,
                quickClose: true,
                padding:10
            });
            d.show(obj);
        }else{
            var d = dialog();
            d.content(msg).show();
            setTimeout(function () {
                d.close().remove();
            }, 2000);
        }
    };
});